<?php
App::uses('AppController', 'Controller');
/**
 * Products Controller
 *
 * @property Product $Product
 */
class ProductsController extends AppController {

	public function beforeFilter() {
		parent::beforeFilter();
		Controller::loadModel('Parameter');
		$this->set('status', $this->Parameter->getProductStatus()); // status array of users
	}

/**
 * index method
 *
 * @return void
 */
	public function admin_index() {
		$this->Product->recursive = 0;
		$variant = $this->Product->Variant->find('first', array('conditions' => array('is_master' => true)));
		$this->set('mainVariant', $variant);
		$this->set('products', $this->paginate());
	}

/**
 * view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function admin_view($id = null) {
		$this->Product->id = $id;
		if (!$this->Product->exists()) {
			throw new NotFoundException(__('Invalid product'));
		}
		$this->set('product', $this->Product->read(null, $id));
	}

/**
 * add method
 *
 * @return void
 */
	public function admin_add() {
		Controller::loadModel('Variant');
		Controller::loadModel('Category');
		if ($this->request->is('post')) {
			$this->Product->create();
			$this->request->data['Product']['created_at'] = date("Y-m-d H:i:s");
			$this->request->data['Product']['created_by'] = $this->Auth->user('id');

			//Create main variant
			$this->request->data['Variant']['0']['name'] = "All";
			$this->request->data['Variant']['0']['status'] = Variant::active;
			$this->request->data['Variant']['0']['is_master'] = true;
			$this->request->data['Variant']['0']['hand_on'] = $this->request->data['Product']['hand_on'];

			//Create ProductProperty
			$prototype = $this->Product->Prototype->find('first', array('conditions' =>
																																	array('id' => $this->data['Product']['prototype_id'] )));
			foreach($prototype['Property'] as $i => $property){
				$this->request->data['ProductProperty'][$i]['property_id'] = $property['id'];
			}
			if ($this->Product->saveAssociated($this->request->data)) {
				$this->request->data['Product']['id'] = $this->Product->id;
				$this->Session->setFlash(__('The product has been saved'), 'default', array(), 'good');
				#$this->redirect(array('action' => 'index'));
				$this->redirect(array('admin' => true, 'action' => 'edit',$this->Product->id));
			} else {
				$this->Session->setFlash(__('The product could not be saved. Please, try again.'), 'default', array(), 'bad');
			}
		}
		$prototypes = $this->Product->Prototype->find('list');
#		$categories = $this->Product->Category->find('list', array('conditions' => array('type' => Category::products)));
		$categories = $this->Product->Category->generateTreeList(array('type' => Category::products), null, null,  "&raquo;&rarr;&nbsp;&nbsp;");
		$this->set(compact('categories'));
		$this->set(compact('prototypes'));
	}

/**
 * edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function admin_edit($id = null) {	
		$this->Product->id = $id;
		if (!$this->Product->exists()) {
			throw new NotFoundException(__('Invalid product'));
		}
		if ($this->request->is('post') || $this->request->is('put')) {
			$this->request->data['Product']['updated_at'] = date("Y-m-d H:i:s");
			$this->request->data['Product']['updated_by'] = $this->Auth->user('id');
			$this->request->data['Variant']['0']['hand_on'] = $this->request->data['Product']['hand_on'];
			if ($this->Product->saveAssociated($this->request->data)) {
				$this->Session->setFlash(__('The product has been saved'), 'default', array(), 'good');
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The product could not be saved. Please, try again.'), 'default', array(), 'bad');
			}
		} else {
			$this->request->data = $this->Product->read(null, $id);
		}
		$prototypes = $this->Product->Prototype->find('list');
		$this->Product->Variant->recursive = -1; //for without joining associated table
		$variant = $this->Product->Variant->find('first', array('conditions' => array('is_master' => true)));
		$this->request->data['Variant']['0'] = $variant['Variant'];
		#$categories = $this->Product->Category->find('list', array('conditions' => array('type' => Category::products)));
		$categories = $this->Product->Category->generateTreeList(array('type' => Category::products), null, null,  "&raquo;&rarr;&nbsp;&nbsp;");
		$this->set(compact('categories'));
		$this->set(compact('prototypes'));
		//select tab
		if(isset($_REQUEST['select']) && !empty($_REQUEST['select'])){
			$select =  $_REQUEST['select'];
			$this->set("tab", $select);
		}
	}

/**
 * delete method
 *
 * @throws MethodNotAllowedException
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function admin_delete($id = null) {
		if (!$this->request->is('post')) {
			throw new MethodNotAllowedException();
		}
		$this->Product->id = $id;
		if (!$this->Product->exists()) {
			throw new NotFoundException(__('Invalid product'));
		}
		if ($this->Product->delete()) {
			$this->Session->setFlash(__('Product deleted'), 'default', array(), 'good');
			$this->redirect(array('action' => 'index'));
		}
		$this->Session->setFlash(__('Product was not deleted'), 'default', array(), 'bad');
		$this->redirect(array('action' => 'index'));
	}

/**
 * load Product Form ajax
 *
 */
	public function admin_loadProductForm($id = null){
		if(!$this->request->is('ajax')){
			throw new BadRequestException(__('Invalid Request'));
		}
		$prototypes = $this->Product->Prototype->find('list');
		$this->set(compact('prototypes'));
		$this->render('ProductForm', 'ajax');
	}

/**
 * load properties ajax
 * 
 */
	public function admin_loadProperties($id=null){
		Controller::loadModel('ProductProperty');
		$this->Product->id = $id;
		if (!$this->Product->exists()) {
			throw new NotFoundException(__('Invalid product'));
		}

		if ($this->request->is('post') || $this->request->is('put')) {
			//Get deleted properties
			$currentProductPropertyIds = array();
			$oldProductPropertyIds = array();
			foreach($this->request->data['ProductProperty'] as $pro){
				array_push($currentProductPropertyIds, $pro['id']);
			}
			$productProperties = $this->ProductProperty->find('list', array('conditions' => array('product_id' => $id)));
			foreach($productProperties as $pro){
				array_push($oldProductPropertyIds, $pro);
			}
			$deletedIds = array_diff($oldProductPropertyIds, $currentProductPropertyIds);
			//Update properties
			$this->ProductProperty->create();
			if($this->ProductProperty->saveMany($this->request->data['ProductProperty'])){
				//detele product properties
				foreach($deletedIds as $id){
					$this->ProductProperty->id = $id;
					$this->ProductProperty->delete();
				}
				$this->Session->setFlash(__('The product has been saved'), 'default', array(), 'good');
			}else{
				$this->Session->setFlash(__('The product could not be saved. Please, try again.'), 'default', array(), 'bad');
			}
			$this->redirect(array('admin' => true, 'action' => 'edit',$this->Product->id, '?' => array('select' => 1)));
		}else{
			if(!$this->request->is('ajax')){
				throw new BadRequestException(__('Invalid Request'));
			}
		}	
		$product = $this->Product->read(null, $id);
		$this->request->data = $product;
		//get properties of product
		$properties = $this->ProductProperty->getPropertiesByProduct($id);
		$this->set('properties', $properties);
		$this->render('PropertyForm', 'ajax');
	}


/** 
 * load images form ajax
 *
 */
	public function admin_loadImageForm($id = null){
		Controller::loadModel('Variant');
		Controller::loadModel('Image');
		$this->Product->id = $id;
		if (!$this->Product->exists()) {
			throw new NotFoundException(__('Invalid product'));
		}

		if ($this->request->is('post') || $this->request->is('put')) {
			$this->Image->create();
			$this->request->data['Image']['owner_model'] = $this->Variant->name;
		
			#parameter image sizes
			$thumbSizes = $this->Parameter->getVariantImageSizes();
			$this->Image->updateVariantSize($this->Variant->name, $thumbSizes);

			#Save image
			if($this->Image->save($this->request->data['Image'])){
				$this->Session->setFlash(__('The Image has been saved'), 'default', array(), 'good');
			}else{
				$this->Session->setFlash(__('The Image could not be saved. Please, try again.'), 'default', array(), 'bad');
			}
			$this->redirect(array('admin' => true, 'action' => 'edit',$this->Product->id, '?' => array('select' => 2)));
		}else{ //when click on tab Images
			if(!$this->request->is('ajax')){
				throw new BadRequestException(__('Invalid Request'));
			}
			//Load all images for variants
			$images = $this->Image->getImagesForProduct($id);
			$this->set('images', $images);
		}
		$this->Product->Variant->recursive = -1;
		$owners = $this->Product->Variant->find('list', array('conditions' => array('product_id' => $id)));
		$this->set(compact('owners', $owners));
		$this->set("id", $id);
		$this->render('ImageForm', 'ajax');
	}

/**
 * Delete Image
 *
 */
	public function admin_deleteImage($id = null, $imageId = null){
		if (!$this->request->is('post')) {
			throw new MethodNotAllowedException();
		}
		Controller::loadModel('Image');
		$this->Image->id = $imageId;
		if (!$this->Image->exists()) {
			throw new NotFoundException(__('Invalid image'));
		}
		if ($this->Image->delete()) {
			$this->Session->setFlash(__('Image deleted'), 'default', array(), 'good');
		}else{
			$this->Session->setFlash(__('Image was not deleted'), 'default', array(), 'bad');
		}
		$this->redirect(array('admin' => true, 'action' => 'edit', $id, '?' => array('select' => 2)));
	}

/** 
 * load variant form ajax
 *
 */
	public function admin_loadVariantList($id = null){
		Controller::loadModel('Variant');
		$this->Product->id = $id;
		if(!$this->request->is('ajax')){
			throw new BadRequestException(__('Invalid Request'));
		}

		$this->Product->Variant->recursive = -1;
		$variants = $this->Product->Variant->find('all', array('conditions' => 
																					array('product_id' => $id, 'is_master' => false, 'status' => Variant::active)));
		$this->set('variants', $variants);
		$this->set('id', $id);
		$this->render('VariantList', 'ajax');
	}

/**
 * load variant form ajax
 *
 */
	public function admin_loadVariantForm($id = null){
		Controller::loadModel('Variant');
		Controller::loadModel('OptionValue');
		$this->Product->id = $id;
		if (!$this->Product->exists()) {
			throw new NotFoundException(__('Invalid product'));
		}
		//when submit create a variant
		if ($this->request->is('post') || $this->request->is('put')) {
			//Mode New
			if(empty($this->request->data['Variant']['id']) || !isset($this->request->data['Variant']['id'])){
				$this->Product->Variant->create();
				$this->request->data['Variant']['product_id'] = $id;
				$this->request->data['Variant']['status'] = Variant::active;
	
				//generate variant name
				$name = "";
				foreach($this->request->data['OptionValue']['OptionValue'] as $value){
					$optionValue = $this->OptionValue->findById($value);
					if(isset($optionValue)){
						$name .= " + " . $optionValue['OptionType']['name'] . ": " . $optionValue['OptionValue']['name'];
					}
				}
				$this->request->data['Variant']['name'] = $name;
			}
			if($this->Product->Variant->saveAssociated($this->request->data)){
				$this->Session->setFlash(__('The Variant has been saved'), 'default', array(), 'good');
			}else{
				$this->Session->setFlash(__('The Variant could not be saved. Please, try again.'), 'default', array(), 'bad');
			}
			$this->redirect(array('admin' => true, 'action' => 'edit', $id, '?' => array('select' => 3)));
		}else{
			if(!$this->request->is('ajax')){
				throw new BadRequestException(__('Invalid Request'));
			}

			if(isset($_REQUEST["vid"])){
				$this->Variant->id = $_REQUEST["vid"];
				$variant = $this->Variant->read(null, $_REQUEST["vid"]);
				$this->request->data = $variant;
			}else{
				//get price base on master
				$variant = $this->Product->Variant->find('first', array('conditions' => array('is_master' => true)));
				if(isset($variant)){
					$this->request->data['Variant']['raw_price'] = $variant['Variant']['raw_price'];
					$this->request->data['Variant']['price'] = $variant['Variant']['price'];
					$this->request->data['Variant']['hand_on'] = $variant['Variant']['hand_on'];
				}
			}

			$product = $this->Product->read(null, $id);
			$prototype = $this->Product->Prototype->findById($product['Prototype']['id']);
			$this->set('prototype', $prototype);
			$this->render('VariantForm', 'ajax');
		}
	}

/**
 * delete variant
 *
 */
	public function admin_deleteVariant($id = null, $variantId = null){
		if (!$this->request->is('post')) {
			throw new MethodNotAllowedException();
		}
		Controller::loadModel('Variant');
		$this->Variant->id = $variantId;
		if (!$this->Variant->exists()) {
			throw new NotFoundException(__('Invalid variant'));
		}
		if ($this->Variant->delete()) {
			$this->Session->setFlash(__('Variant deleted'), 'default', array(), 'good');
		}else{
			$this->Session->setFlash(__('Variant was not deleted'), 'default', array(), 'bad');
		}
		$this->redirect(array('admin' => true, 'action' => 'edit', $id, '?' => array('select' => 3)));
	}
}
